# -*- coding: utf-8 -*-

"""
矩形拼板可视化工具
用于可视化pdf_rectangle_nesting.py生成的拼板结果
"""

import os
import json
import argparse
from PIL import Image, ImageDraw

class NestingVisualizer:
    """拼板结果可视化类"""
    def __init__(self, results_path, output_dir):
        self.results_path = results_path
        self.output_dir = output_dir
        self.results = {}
        self.colors = [
            (255, 0, 0),    # 红色
            (0, 255, 0),    # 绿色
            (0, 0, 255),    # 蓝色
            (255, 255, 0),  # 黄色
            (255, 0, 255),  # 洋红色
            (0, 255, 255),  # 青色
            (192, 192, 192), # 灰色
            (128, 0, 0),    # 深红色
            (128, 128, 0),  # 橄榄绿
            (0, 128, 0),    # 深绿色
            (128, 0, 128),  # 紫色
            (0, 128, 128),  # 深青色
            (0, 0, 128),    # 深蓝色
            (255, 165, 0),  # 橙色
            (210, 180, 140), # 棕色
            (255, 192, 203)  # 粉色
        ]
    
    def load_results(self):
        """加载拼板结果JSON文件"""
        try:
            with open(self.results_path, 'r', encoding='utf-8') as f:
                self.results = json.load(f)
            print(f"成功加载拼板结果: {self.results_path}")
            return True
        except Exception as e:
            print(f"加载拼板结果时出错: {str(e)}")
            return False
    
    def create_visualization(self, filename="nesting_visualization.png", scale=0.1):
        """创建可视化图像"""
        if not self.results:
            print("请先加载拼板结果")
            return False
        
        try:
            # 获取拼板参数
            width_limit = self.results.get('width_limit', 1000)
            total_length = self.results.get('total_length', 1000)
            rectangles = self.results.get('rectangles', [])
            
            # 应用缩放因子
            scaled_width = int(width_limit * scale)
            scaled_height = int(total_length * scale)
            
            # 创建白色背景图像
            image = Image.new('RGB', (scaled_width + 20, scaled_height + 20), color='white')
            draw = ImageDraw.Draw(image)
            
            # 绘制每个矩形
            for i, rect in enumerate(rectangles):
                # 应用缩放
                x = int(rect['x'] * scale) + 10  # +10 为了边距
                y = int(rect['y'] * scale) + 10
                width = int(rect['width'] * scale)
                height = int(rect['height'] * scale)
                
                # 选择颜色
                color_index = i % len(self.colors)
                fill_color = self.colors[color_index]
                border_color = (0, 0, 0)  # 黑色边框
                
                # 绘制矩形
                draw.rectangle([(x, y), (x + width, y + height)], fill=fill_color, outline=border_color, width=1)
                
                # 绘制矩形索引
                text_x = x + width // 2
                text_y = y + height // 2
                draw.text((text_x, text_y), str(rect['index']), fill=border_color, anchor='mm')
                
                # 如果矩形旋转了，添加旋转标记
                if rect.get('rotated', False):
                    draw.line([(x, y), (x + width, y + height)], fill='black', width=1)
            
            # 添加标题和信息
            title = f"矩形拼板结果 (宽度限制: {width_limit}mm, 总长度: {total_length}mm)"
            draw.text((scaled_width // 2 + 10, 5), title, fill='black', anchor='mt')
            
            # 确保输出目录存在
            os.makedirs(self.output_dir, exist_ok=True)
            
            # 保存图像
            output_path = os.path.join(self.output_dir, filename)
            image.save(output_path)
            print(f"拼板可视化结果已保存到: {output_path}")
            
            return output_path
        except Exception as e:
            print(f"创建可视化图像时出错: {str(e)}")
            return False


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='矩形拼板可视化工具')
    parser.add_argument('--results-path', type=str, required=True, help='拼板结果JSON文件路径')
    parser.add_argument('--output-dir', type=str, default='nesting_visualizations', help='输出目录路径')
    parser.add_argument('--scale', type=float, default=0.1, help='缩放因子，用于控制图像大小')
    
    args = parser.parse_args()
    
    # 创建可视化实例
    visualizer = NestingVisualizer(args.results_path, args.output_dir)
    
    # 加载结果并创建可视化
    if visualizer.load_results():
        visualizer.create_visualization(scale=args.scale)

if __name__ == '__main__':
    main()